﻿using Microsoft.Extensions.DependencyInjection;

namespace Foundation.Core
{
    public class SelectItemLoadMethodConverterFactory : ISelectItemLoadMethodConverterFactory
    {
        public ISelectItemLoadMethodConverter Create(SelectItemLoadMethodOptions options)
        {
            return new SelectItemLoadMethodConverter(options);
        }

        public static ISelectItemLoadMethodConverter GetConverter(IServiceProvider serviceProvider, SelectItemLoadMethodOptions methodOptions)
        {
            var converter = methodOptions.ParamaterConverter;
            if (converter != null) return methodOptions.ParamaterConverter;

            var factoryType = methodOptions.ParamaterConverterTypeFactory ?? typeof(SelectItemLoadMethodConverterFactory);

            var factory = serviceProvider.GetRequiredService(factoryType) as ISelectItemLoadMethodConverterFactory;

            if (factory != null)
            {
                converter = factory.Create(methodOptions);

                if (factoryType == typeof(SelectItemLoadMethodConverterFactory))
                {
                    methodOptions.ParamaterConverter = converter;
                }
            }
            else
            {
                throw new BusinessException("select_method_creator_MethodConvertNull", $"参数转换器工厂为null");
            }

            return converter;
        }

    }
}
